package com.xxxx.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.xxxx.server.pojo.*;
import com.xxxx.server.service.*;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhoubin
 * @since 2022-04-13
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {
    @Autowired
    private  IDepartmentService departmentService;
    @Autowired
    private IJoblevelService joblevelService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private INationService nationService;
    @ApiOperation("获取员工分页")
    @GetMapping("/")
    public RespPageBean getemployeepage(@RequestParam(defaultValue = "1") Integer currentPage,@RequestParam(defaultValue = "10") Integer size, Employee employee, LocalDate[] beginDateScope){
    return  employeeService.employeepage(currentPage,size,employee,beginDateScope);
    }



    @ApiOperation("获取所有政治面貌")
    @GetMapping("/politicsstatus")
    public List<PoliticsStatus> getAllPoliticsStatus(){
        return politicsStatusService.list();
    }

    @ApiOperation("获取所有职称")
    @GetMapping("/joblevels")
    public List<Joblevel> getAllJoblevels(){
        return joblevelService.list();
    }

    @ApiOperation("获取所有民族")
    @GetMapping("/nations")
    public List<Nation> getAllNations(){
        return nationService.list();
    }

    @ApiOperation("获取所有职位")
    @GetMapping("/positions")
    public List<Position> getAllPositions(){
        return positionService.list();
    }

    @ApiOperation("获取所有部门")
    @GetMapping("/deps")
    public List<Department> getAllDepartments(){
        return departmentService.getalldep();
    }

    @ApiOperation("获取工号")
    @GetMapping("/maxWorkID")
    public RespBean getmaxworkid(){
       return employeeService.getmaxid();
    }

    @ApiOperation("更新员工")
    @PutMapping("/")
    public RespBean updateemployee(@RequestBody Employee employee){
        if (employeeService.updateById(employee)){
            return RespBean.success("更新成功");
        }else {
            return RespBean.error("更新失败");
        }
    }


    @ApiOperation("删除员工")
    @DeleteMapping("/{id}")
    public RespBean deleteemployee(@PathVariable("id") Integer id){
        if (employeeService.removeById(id)){
            return RespBean.success("删除成功");
        }else {
            return RespBean.error("删除失败");
        }
    }


    @ApiOperation("添加员工")
    @PostMapping("/")
    public RespBean addemplyoee(@RequestBody Employee employee){
        return employeeService.addemployee(employee);
    }



    @ApiOperation(value = "导出员工数据")
    //防止输出乱码，提示用流的形式输出
    @GetMapping(value = "/export",produces ="application/octet-stream")
    public void exporEmployee(HttpServletResponse response){
        List<Employee> list =employeeService.getemployee(null);
        //HSSF 03版导出快一些 XSSF 07版导出慢一些
        ExportParams params = new ExportParams("员工表","员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params,Employee.class,list);
        ServletOutputStream outputStream=null;
        try{
            response.setHeader("content-type","application/octet-stream");
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8"));
            outputStream=response.getOutputStream();
            workbook.write(outputStream);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (null!=outputStream){
                try {
                    outputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }

    }



    @ApiOperation("导入员工数据")
    @PostMapping("/import")
    public RespBean importEmplyee(MultipartFile file){
        ImportParams params = new ImportParams();
        //弃掉标题行
        params.setTitleRows(1);
        List<Nation> nationList=nationService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        List<Department> departmentList =departmentService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<Position> positionList =positionService.list();
        try{
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(),Employee.class,params);
            list.forEach(employee -> {
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
                employee.setPoliticId( politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
                employee.setDepartmentId(departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId());
                employee.setJobLevelId(joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                employee.setPosId(positionList.get(positionList.indexOf(new Position(employee.getPosition().getName()))).getId());
            });
            if (employeeService.saveBatch(list)){
                return RespBean.success("导入成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }
}
